package pers.lan.stack;

import java.util.Stack;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/9/3 7:41 AM
 */
public class LC_682 {

    public static void main(String[] args) {
        System.out.println(
                new LC_682().calPoints(
                        new String[]{"5", "-2", "4", "C", "D", "9", "+", "+"}
                )
        );
    }

    public int calPoints(String[] ops) {
        Stack<Integer> stack = new Stack<>();
        int sum = 0;
        for (String op : ops) {
            switch (op) {
                case "C":
                    sum -= stack.pop();
                    break;
                case "D":
                    int i1 = stack.peek() * 2;
                    stack.push(i1);
                    sum += i1;
                    break;
                case "+":
                    Integer pop1 = stack.pop();
                    Integer pop2 = stack.pop();
                    stack.push(pop2);
                    stack.push(pop1);
                    stack.push(pop1 + pop2);
                    sum += pop1 + pop2;
                    break;
                default:
                    int s = Integer.parseInt(op);
                    stack.push(s);
                    sum += s;
                    break;
            }
        }
        return sum;
    }

    public int calPoints2(String[] ops) {
        int[] arr = new int[ops.length];
        int i = 0;
        for (String s : ops) {
            switch (s) {
                case "+":
                    arr[i] = arr[i - 1] + arr[i - 2];
                    i++;
                    break;
                case "D":
                    arr[i] = 2 * arr[i - 1];
                    i++;
                    break;
                case "C":
                    arr[i - 1] = 0;
                    i--;
                    break;
                default:
                    arr[i] = Integer.parseInt(s);
                    i++;
            }
        }
        int sum = 0;
        for (int j = 0; j < arr.length; j++) {
            sum += arr[j];
        }
        return sum;
    }
}
